package com.example.test.core.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

@Service
public class RabbitMQService implements RabbitTemplate.ConfirmCallback {

    private static final Logger log = Logger.getLogger("RabbitMQService");
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送成功");
        } else {
            log.info("消息发送失败:" + cause);
        }
    }

    //发送消息，不需要实现任何接口，供外部调用。
    public void convertSendAndReceive(String msg) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        log.info("开始发送消息 : " + msg.toLowerCase());
        String response = rabbitTemplate.convertSendAndReceive("TopicExchange", "key.one", msg, correlationId).toString();
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(response, new TypeToken<Map<String, Object>>() {
        }.getType());
        log.info("结束发送消息 : " + msg.toLowerCase());
        log.info("消费者响应结果 : " + map.get("result") + " ，响应消息：" + map.get("message"));
    }

    public void send(String msg) {
        log.info("开始发送消息2 : " + msg);
        Message message = new Message(msg.getBytes(), new MessageProperties());
        rabbitTemplate.send("TopicExchange", "key.two", message);
        log.info("结束发送消息2 : " + msg);
    }
}